import { defineStore } from 'pinia'
import i18n from '~/i18n/index'

export const useAppStore = defineStore('app', () => {
  const pending = ref(new Set<string>())
  const user = ref<UaaUserDetails>()
  const token = ref<string>()
  const globalLoading = ref(false)
  const globalText = ref('')
  const version = '0.0.1'
  const defaultPage = '/'
  const initRoute = ref(false)

  function delPending(id: string) {
    pending.value.delete(id)
  }

  function initOauth(auth: OAuthRes) {
    cache.setToken(auth.accessToken || '')
    cache.setTokenExpires(auth.expires || 0)
    cache.setRefreshToken(auth.refreshToken || '')
  }

  function initMenu(allMenus: Array<Menu>) {
    initRoute.value = true
  }

  function initial(u: UaaUserDetails) {
    user.value = u
    token.value = u.token
  }

  function setGlobalLoading(v: boolean, t: string) {
    globalLoading.value = v
    globalText.value = t
  }

  function cleanGlobalLoading() {
    globalLoading.value = false
    globalText.value = ''
  }

  const logined = computed(() => user.value != undefined)
  const loading = computed(() => pending.value.size > 0)

  function changeLang(lang: 'zhCn' | 'enUs' | 'ruRu') {
    i18n.global.locale.value = lang
    localStorage.setItem('localeLang', lang)
    // setVantLang()
  }

  function setVantLang() {
    const lang = localStorage.getItem('localeLang') || 'ruRu'
    // if (lang == 'ruRu') Locale.use('ru-RU', ruRu)
    // if (lang == 'zhCn') Locale.use('zh-CN', zhCN)
  }
  return {
    pending,
    user,
    token,
    loading,
    initMenu,
    delPending,
    initOauth,
    initial,
    logined,
    version,
    initRoute,
    defaultPage,
    changeLang,
    globalLoading,
    globalText,
    setGlobalLoading,
    cleanGlobalLoading
  }
})
